package com.example.demo.leetcode.top;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class Test2 {


      public static class ListNode {
          int val;
          ListNode next;
          ListNode(int x) { val = x; }
      }


    public  static ListNode reverseList(ListNode head) {
          if(head == null){
              return null;
          }
          if(head.next == null){
              return head;
          }

          ListNode node = null;
          List<ListNode> list = new ArrayList<ListNode>();
          while(head.next != null){
              list.add(head);
              head = head.next;
          }
          list.add(head);

          for(int i=list.size()-1;i>=0;i--){
              if(i == 0){
                list.get(i).next = null;
                break;
              }
              if(i == list.size()-1){
                  node = list.get(i);
              }
              list.get(i).next = list.get(i-1);
          }
        return node;
    }

    public static ListNode initList(int [] arr){
          ListNode head = null;
          List<ListNode> list = new ArrayList<ListNode>();
          for(int i=0;i<arr.length;i++){
              ListNode node = new ListNode(arr[i]);
              if(i == 0){
                  head = node;
              }
               list.add(node);
          }
          for(int i=0 ;i<list.size()-1; i++){
              list.get(i).next = list.get(i+1);
              if(i == list.size()-2){
                  list.get(i+1).next = null;
              }
          }
            return head;
    }

    public static void printf(ListNode listNode){
          while(listNode.next!=null){
              System.out.printf(listNode.val+" ");
              listNode = listNode.next;
          }
        System.out.printf(listNode.val+" ");
    }

    public static void main(String[] args) {
        int [] arr = {1,2,3,4,5};
        ListNode listNode = initList(arr);
        printf(listNode);
        ListNode listNode2 = reverseList(listNode);
        printf(listNode2);
    }

}
